﻿<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>居中弹窗</title>
    <style>
    body{padding-top:1000px;}
    ul {
        margin: 0;
        padding: 0;
        list-style: none;
    }
    .popover{display:none;position:absolute;left:200px;top:100px;width:300px;height:200px;border:1px solid #ccc;background-color:#fff;}
    .popover .title{height:50px;line-height:50px;padding:0 10px;background:linear-gradient(#fff, #efefef 5%, #ddd);}
    .popover .content{padding:15px;}
    .popover .footer{position:absolute;left:0;bottom:0;right:0;padding:20px;text-align:center;}
    .footer button{display:inline-block;margin:0 5px;padding:5px 15px;border:1px solid #ddd;background:linear-gradient(#efefef, #cfcfcf);}
    </style>
    <script src="../../../课件/jquery-2.1.1.min.js" type="text/javascript" charset="utf-8"></script>
    <script>
        $(function(){
            /*
                实现居中弹窗
                    $(window).scrollTop():窗口垂直滚动条滚动过的距离
                    $(window).scrollLeft():窗口水平滚动条滚动过的距离
                    left:($(window).width()-$pop.outerWidth())/2 + $(window).scrollLeft()
                    top:($(window).height()-$pop.outerHeight())/2 + $(window).scrollTop()
             */
            var $pop = $('.popover');
            // 点击弹窗
            $('#addPop').on('click',function(e){
                $pop.show();
                popCenter();

                // 阻止连接跳转
                e.preventDefault();
            });

            // 窗口改变时自动居中
            $(window).on('resize scroll',function(){
                popCenter();
            })

            function popCenter(){
                $pop.stop().animate({
                    left:($(window).width()-$pop.outerWidth())/2 + $(window).scrollLeft(),
                    top:($(window).height()-$pop.outerHeight())/2 + $(window).scrollTop()
                });
            }
        });
    </script>
</head>

<body>
    <a href="#" id="addPop">弹窗</a>
    <div class="popover">
        <div class="title">弹窗标题</div>
        <div class="content">弹窗内容</div>
        <div class="footer">
            <button class="ok">确认</button>
            <button class="close">关闭</button>
        </div>
    </div>
</body>

</html>
